/*
 * @Date: 2024-05-26 11:34:22
 * @LastEditors: wkl
 * @LastEditTime: 2024-06-02 21:06:52
 * @FilePath: /demo/双色球/l3.js
 */
const fs = require('fs')
const path = require('path')
const cheerio = require('cheerio')
const superagent = require('superagent')
const { Workbook } = require('exceljs');

let url = `https://datachart.500.com/ssq/history/newinc/history.php?start=23113&end=24061`
let filePath = path.resolve('data/rets.json') // 存放爬取结果的文件地址 这里存放的 json 格式
let pathHtml = path.resolve('line-stack.html')
let pathHtmlSouce = path.resolve('line-stack-copy.html')

async function getComposition() { // 爬取html
    const responseRet = await superagent.get(url)
    const responseHtml = responseRet.text
    return responseHtml
}

function getTargetData(html) { // 解析 html 串，变成数据

    const $ = cheerio.load(html)
    // 先找到 tr 然后拿 a 和 第二个td 里的内容
    const trList = $('#tablelist').find('.t_tr1')

    let retData = {}

    trList.map((index, item) => {

        const tdList = $(item).find('td')

        const issue = $(tdList[0]).text()

        let reds = ''
        for (let i = 1; i < 7; i++) {
            if (i < 6) {
                reds += $(tdList[i]).text() + ','
            } else {
                reds += $(tdList[i]).text()
            }
        }
        const blue = $(tdList[7]).text()

        retData[issue] = reds + ' - ' + blue
    })

    return retData
}

function assemblyData(data) {  // 处理数据，变成我们最终想要的那个格式
    let fileData = {}
    Reflect.ownKeys(data)
        .sort((a, b) => Number(a) - Number(b))
        .map(item => {
            fileData[String(item)] = data[String(item)]
        })

    return JSON.stringify(fileData, null, '\t')
}


// 读取html
function readFileHtml(insertHtml) {
    // 异步读取HTML文件
    fs.readFile(pathHtmlSouce, 'utf8', (err, data) => {
        if (err) {
            // console.error('读取文件时发生错误:', err);
            return;
        }

        fs.writeFileSync(pathHtml, insertHtml + data)
        // 输出HTML文件的内容
        // console.log(data);
    });
}

// 计算出现次数
function countElements(arr) {
    return arr.reduce((countMap, item) => {
        countMap[item] = (countMap[item] || 0) + 1;
        return countMap;
    }, {});
}


// 获取前{5}最大值
function getTopFiveLargest(arr, maxNumber = 5,index) {
    // 对数组进行降序排序
    arr.sort(function (a, b) {
        return b - a;
    });

    // 返回前5个最大的元素
    if(index==3){
        console.log(arr.slice(0, maxNumber))
    }   
   
    return arr.slice(0, maxNumber);
}


// 


// 指定筛选数据
function getTopFiveLargestNum(data, arr,index) {
    let tarr=[]
    let topFiveLargestArr = Object.values(data)
    var item = getTopFiveLargest(topFiveLargestArr,5,index)
    // item=Array.from(new Set(item))
    item.forEach((item,_index) => {
        for (const key in data) {
           if(data[key]===item){
            if(!arr[index]){
                arr[index]=[]
            }
            tarr.push(key)
           }
        }
    })
    return tarr.toString()
}


// 统计
function statistics(result,sourceData) {
    // 筛选5组数据
    let tempFiterArr = []

    let echartsData = []
    let obj1 = new Map()
    let obj = {}
    let tempArr = []
    let arr = Object.values(result)
    arr.forEach(item => {
        item = item.replace(' - ', ',')
        let temp = item.split(',')
        temp = temp.map(item => Number(item))
        tempArr.push(temp)
    })

    tempArr.forEach((item, index) => {
        item.forEach((_item, _index) => {
            if (obj[_index]) {
                obj[_index].push(_item)
            } else {
                obj[_index] = []
                obj[_index].push(_item)
            }
        })
    })

    let arr1 = Object.values(obj)

    arr1.forEach(((item, index) => {
        let ydata = []
        let xdata = []
        obj1.set('第' + index + '列', countElements(item))
        let data = obj1.get('第' + index + '列')
        xdata = Object.values(data).map((item, index) => index)
        for (const key in data) {
            ydata.push(data[key])
        }

        tempEchartsData = {
            x: xdata,
            type: 'line',
            data: ydata,
            top: getTopFiveLargestNum(data, tempFiterArr,index)
        }
        echartsData.push(tempEchartsData)
       
    }))



    // 7列组合
    let arr7=[]
    echartsData.forEach((_item,_index)=>{
        let arr = _item.top.split(',')
        arr.forEach((item,index)=>{
            if(index<=4){
                if(!arr7[index]){
                    arr7[index]=[]
                }
                arr7[index].push(item)
            }
        })
    })



    diffData(formatData(sourceData),arr7)


    let insertHtml = `<script type="text/javascript">let data = ${JSON.stringify(echartsData)}</script>`
    readFileHtml(insertHtml)
    // console.log(obj1)
}

// 

// 100 条数据配对
function diffData(data,arr7){
    let diffCounlm=2
    let arr1 =['2,8,17,22,25,33,4','1,6,20,17,23,32,3','3,7,11,18,26,31,15','5,9,12,25,26,27,8','7,10,13,14,27,30,16']
    arr1 = arr7.map((item)=>{
        item = item.slice(0, diffCounlm)
        item.toString()
        console.log(item,'-0-=')
        return item
    })
   
    winningFun(data,arr1,diffCounlm)
}

function winningFun(data,arr1,diffCounlm){
    console.log("对比"+diffCounlm+"条数据")
    data.forEach(item=>{
        item=item.toString()
        arr1.forEach((_item)=>{
            if(item.includes(_item)){
                console.log(item,'恭喜中奖')
            }
        })
    })
}



// excel 
async function excel(data) {
    // 创建一个新的工作簿
    const workbook = new Workbook();
    // 添加一个新的工作表，命名为'hong'
    const worksheet = workbook.addWorksheet('hong');

    // 定义工作表的列结构
    worksheet.columns = [];

    // 向工作表中添加数据行
    worksheet.addRows(data);

    // 将工作簿保存为Excel文件
    workbook.xlsx.writeFile('./data2.xlsx');
}

//格式化数据
function formatData(data) {
    let a1 = Object.values(JSON.parse(data))
    a1 = a1.map((item => {
        item = item.replace(' - ', ',')
        item = item.split(',')
        return item
    }))
    return a1
}

function executeWrite(data) { // 写入文件
    let result = JSON.parse(data)
    statistics(result,data)
    excel(formatData(data))
    fs.writeFileSync(filePath, data)
    // diffData(formatData(data))
}



(async () => { // 自调用直接执行匿名函数

    const retHtml = await getComposition()

    const retData = getTargetData(retHtml)

    const fileData = assemblyData(retData)

    executeWrite(fileData)

})()

//TODO
// 1 统计出第一列所有的数据 ～7列
// 2 找出每列出现的数字
// 7列组合10组数据

